package security;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bean.UserObject;

public class CoreSecurityManager {

	protected static Log log = LogFactory.getLog(CoreSecurityManager.class);

	public static List<CoreRoleEnum> getRolesFromAuthBit(String auth) {
		List<CoreRoleEnum> list = new ArrayList<CoreRoleEnum>();
		for (int i = 0; i < CoreRoleEnum.ROLES.length; i++) {
			CoreRoleEnum role = CoreRoleEnum.ROLES[i];
			if (authorize(auth, role.getRoleBit())) {
				list.add(role);
			}
		}
		return list;
	}

	public static boolean authorize(String authString, long role) {
		
		long auth = Long.parseLong(authString);
		
		if (auth == 0) {
			return false;
		}
		return (auth & role) == auth;
	}

	public static boolean authorizeAll(HttpServletRequest request,
			CoreRoleEnum[] roles) {
		
		UserObject userObject = (UserObject) request.getSession().getAttribute(
				UserObject.USER_OBJECT_KEY);
		
		for (int i = 0; i < roles.length; i++) {
			CoreRoleEnum role = roles[i];
			if (!authorize(userObject.getAuth(), role.getRoleBit())) {
				return false;
			}
		}
		return true;
	}

	public static boolean authorizeAny(HttpServletRequest request,
			CoreRoleEnum[] roles) {
		
		UserObject userObject = (UserObject) request.getSession().getAttribute(
				UserObject.USER_OBJECT_KEY);
		
		for (int i = 0; i < roles.length; i++) {
			CoreRoleEnum role = roles[i];
			if (authorize(userObject.getAuth(), role.getRoleBit())) {
				return true;
			}
		}
		return false;
	}

	public static boolean authorize(HttpServletRequest request,
			CoreRoleEnum role) {
		
		UserObject userObject = (UserObject) request.getSession().getAttribute(
				UserObject.USER_OBJECT_KEY);
		
		return authorize(userObject.getAuth(), role.getRoleBit());
	}

	public static boolean authorizeURL(HttpServletRequest request) {
		
		UserObject userObject = (UserObject) request.getSession().getAttribute(
				UserObject.USER_OBJECT_KEY);
		
		if (userObject != null) {
			 long auth = CorePathToAuth.getAuth(request);
			return authorize(userObject.getAuth(), auth);
		} else {
			return false;
		}
	}
}
